<template>
  <div>
    <!--搜索卡片-->
    <el-card class="box-card" :body-style="{ padding: '10px',height:'30px'}">
      <el-form :inline="true" :model="searchRoom" ref="ruleForm" class="demo-form-inline">
        <el-form-item label="房间" prop="roomName">
          <el-input size="small" v-model="searchRoom.roomName" placeholder="房间" style="width: 180px"></el-input>
        </el-form-item>
        <el-form-item label="房间类型" prop="typeId">
          <el-select v-model="searchRoom.typeId" placeholder="请选择房间类型" clearable size="small"
                     style="width: 180px;">
            <el-option v-for="(item, index) in options" :key="index" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房东" prop="hotelId">
          <el-input size="small" v-model="searchRoom.hotelId" placeholder="房东" style="width: 180px"></el-input>
        </el-form-item>
        <el-form-item label="房屋状态" prop="status">
          <el-select v-model="searchRoom.status" placeholder="房屋状态" clearable size="medium" style="width: 180px;">
            <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" round size="small" @click="onSearch">查询</el-button>
          <el-button type="warning" round size="small" @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="Button">

      <el-button size="small" type="primary" @click="addRoom" icon="el-icon-plus" plain
                 v-if="userPermissions === 'ADMIN'">新增
      </el-button>
      <el-button size="small" type="danger" @click="deleteBatch" icon="el-icon-delete-solid" plain>批量删除</el-button>
      <el-button size="small" type="primary" @click="uploadExcelDialog = true" plain>导入</el-button>
      <el-button size="small" type="primary" @click="downloadExcel" plain>导出</el-button>

    </div>

    <!--数据表格-->
    <el-table :data="tableData" style="width: 100%;" max-height="100%"
              @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column prop="id" label="序号" width="160"></el-table-column>
      <el-table-column prop="roomName" label="房间" width="160"></el-table-column>
      <el-table-column prop="status" label="状态" width="160">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status === 'Y' ? 'primary' : 'danger'"
            disable-transitions>{{ scope.row.status == "Y" ? '空闲' : '占用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="typeId" label="房屋类型" width="160">
        <template slot-scope="scope">
          {{ getRoomTypeName(scope.row.typeId) }}
        </template>
      </el-table-column>
      <el-table-column prop="hotelId" label="房东" width="160"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200"></el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button
            v-if="userPermissions === 'ADMIN'"
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--新增弹框-->
    <el-dialog class="editDialog" :title="title" v-bind="$attrs" v-on="$listeners" :visible.sync="editRoomDialog"
               @close="onClose">
      <el-form ref="editRoom" :model="editRoom" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="房间" prop="roomName">
          <el-input v-model="editRoom.roomName" placeholder="请输入房间" :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="房屋类型" prop="typeId">
          <el-select v-model="editRoom.typeId" placeholder="请选择房屋类型" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in options" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房屋状态" prop="status">
          <el-select v-model="editRoom.status" placeholder="请选择房屋状态" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="resetEditForm('editRoom')">取消</el-button>
        <el-button type="primary" @click="saveRoom('editRoom')">确定</el-button>
      </div>
    </el-dialog>

    <!--上传execl弹窗-->
    <!--弹窗区域-->
    <el-dialog
      title="上传房间信息"
      width="26%"
      :visible.sync="uploadExcelDialog"
      :close-on-click-modal="false"
    >
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        action=""
        :before-upload="beforeUpload"
        :file-list="fileList"
        :http-request="uploadExcelFun"
        :on-change="handleChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadExcelDialog = false">取 消</el-button>
        <el-button type="primary" @click="">确 定</el-button>
      </div>
    </el-dialog>

    <!--分页查询-->
    <el-card class="box-card" :body-style="{ padding: '10px',height:'20px'}">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchRoom.pageNum"
        :page-sizes="[7, 12, 17, 22]"
        :page-size="searchRoom.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total">
      </el-pagination>

    </el-card>

  </div>
</template>

<script>
import {addRoom, delRoomBatch, delRoomById, editRoom, findRoomType, getRoomList, uploadExcel} from "@/api/room/room";
import {error} from "autoprefixer/lib/utils";

export default {
  name: "Room",
  data() {
    return {
      uploadExcelDialog: false,
      file: null,
      fileList: [],
      editRoomDialog: false,
      tableData: [],
      searchRoom: {  // 查询条件
        roomName: '',
        typeId: null,
        hotelId: null,
        status: null,

        pageNum: 1,// 当前页面
        pageSize: 7,// 每页大小
      },
      editRoom: {
        roomName: null,
        typeId: null,
        status: null,
        hotelId: null,
      },
      options: [],

      total: 0, // 总条数

      userPermissions: null, // 权限验证，若是房东，可以编辑房屋信息

      title: '添加房间',
      multipleSelection: [],
      rules: {
        roomName: [{
          required: true,
          message: '请输入房间',
          trigger: 'blur'
        }],
        typeId: [{
          required: true,
          message: '请选择房屋类型',
          trigger: 'change'
        }],
        status: [{
          required: true,
          message: '请选择房屋状态',
          trigger: 'change'
        }],
      },
      statusOptions: [{
        "label": "空闲",
        "value": "Y"
      }, {
        "label": "占用",
        "value": "N"
      }],
    }
  },
  methods: {
    // 上传文件前清空之前的文件
    beforeUpload(file) {
      this.fileList = []; // 清空文件列表
      return true;
    },

    uploadExcelFun() { // 上传文件方法
      const file = this.file;
      const formData = new FormData(); // 存表单数据

      formData.append('file', file); // 将文件添加到 FormData
      uploadExcel(formData).then((res) => {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        // 上传成功后添加到文件列表
        this.fileList.push({
          name: file.name,
        }); // 上传成功后添加到文件列表
        this.uploadExcelDialog = false; // 关闭弹窗
        this.pageNum = 1; // 刷新为第一页
        this.findAll(); // 刷新
      });
    },
    // 监听文件改变
    handleChange(file) {
      console.log("file", file)
      this.file = file.raw;
    },

    // 下载execl
    downloadExcel(){
      this.$confirm('确定下载？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href = 'http://localhost:9999/room/download/excel';
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消下载'
        });
      });
    },


    // 查询全部数据
    findAll() {
      console.log(this.searchRoom)
      getRoomList(this.searchRoom).then(res => {
        // console.log('查询全部: ', res)
        // console.log(this.$store.getters.id)
        if (res.code === 20000) {
          this.tableData = res.data.list;
          this.total = res.data.total;
        }
      }).catch(error => {
        console.log('请求查询全部报错: ', error)
      })
    },

    // 查询房屋类型
    findRoomType() {
      findRoomType().then(ret => {
        console.log(ret)
        if (ret.code === 20000) {
          console.log('主单位数据: ', ret.data)
          this.options = ret.data.map(item => ({
            value: item.typeId, // 使用 measureId 作为 value
            label: item.typeName // 使用 measureName 作为 label
          }));
          console.log(this.options);

        }
      }).catch(error => {
        console.log('请求查询全部报错: ', error)
      })
    },

    // 添加房间
    addRoom() {
      this.title = "添加房间";
      this.editRoomDialog = true;

    },
    handleEdit(index, row) {
      this.title = "更新房间";
      this.editRoom = row;
      this.editRoomDialog = true;
    },

    // 编辑/添加房间
    saveRoom(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === "添加房间") {
            this.editRoom.hotelId = this.$store.getters.id // 房东id
            console.log('添加房间: ', this.editRoom)
            addRoom(this.editRoom).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '添加成功！',
                  duration: 1000,
                });
                this.editRoomDialog = false;
                this.findAll()
                this.$refs[formName].resetFields();
              } else {
                this.$message({
                  type: 'error',
                  message: '添加失败！',
                  duration: 1000,
                });
                this.editRoomDialog = false;
                this.findAll()
                this.$refs[formName].resetFields();
              }
            }).catch(error => {
              console.log('添加房间报错: ', error)
            })
          } else {
            editRoom(this.editRoom).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '修改成功！',
                  duration: 1000,
                });
                this.editRoomDialog = false;
                this.findAll()
                this.$refs[formName].resetFields();
              }
            })
          }
        } else {
          this.$message({
            type: 'error',
            message: '请填写完整信息！',
            duration: 1000
          });
        }
      })

    },

    // 删除
    handleDelete(index, row) {
      console.log(row.id)
      this.$confirm('是否确认删除用户编号为"' + row.id + '"的信息？', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRoomById(row.id).then(ret => {
          console.log(row.id);
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功！',
              duration: 1000,
            });
            this.findAll();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },


    // 分页查询配置
    handleSizeChange(val) { // 处理页面大小改变时触发
      this.searchRoom.pageSize = val;
      this.findAll()
    },
    handleCurrentChange(val) {// 当前页码改变时触发
      this.searchRoom.pageNum = val;
      this.findAll()
    },

    // 查询
    onSearch() {
      this.findAll()
    },

    resetForm(formName) {  // 重置
      this.$refs[formName].resetFields();
      this.findAll();
    },
    onClose() {
      this.resetEditForm('editRoom'); // 第二次编辑会覆盖问题
    },

    resetEditForm(formName) {
      this.editRoom = {
        roomName: null,
        typeId: null,
        status: null,
        hotelId: null,
      }
      this.$refs[formName].resetFields();
      this.editRoomDialog = false;
    },

    // 批量删除
    deleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择要删除的数据！',
          duration: 1000
        });
      } else {
        this.$confirm('是否确认删除用户编号为"[' + this.multipleSelection + ']"的单位？', '批量删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delRoomBatch({
            ids: this.multipleSelection.join(',')
          }).then(ret => {
            // console.log(ret);
            if (ret.code === 20000) {
              this.$message({
                type: 'success',
                message: '删除成功！',
                duration: 1000
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },
    // 批量删除存的编号数组
    handleSelectionChange(val) {
      this.multipleSelection = [];
      for (const index in val) {
        this.multipleSelection.push(val[index].id); // 取出val中的id
      }
    },
    getRoomTypeName(typeId) {
      const option = this.options.find(option => option.value === typeId);
      return option ? option.label : '未知';
    },
  },

  created() {
    this.userPermissions = this.$store.getters.role;
    this.findAll();
    this.findRoomType();
  }
}
</script>

<style scoped lang="scss">
.box-card {
  width: 100%;
  margin-top: 1px;
  height: 55px;
}

.Button {
  margin-left: 10px;
  margin-top: 10px;
}

.editDialog {
  width: 100%;
}
</style>
